import {getRequest} from "./api";

  export const initMenu = (router, store) => {
    if (store.state.routes.length>0) {
      return;
    }
    getRequest("/system/cfg/menu").then(data => {
      if (data) {
        //格式化router
        console.log(data)
        let fmtRoutes = formatRoutes(data);
        //添加到router
        router.addRoutes(fmtRoutes);
        //将数据存入vuex
        store.commit('initRoutes',fmtRoutes);
        //连接WebSocket
        store.dispatch('connect');
      }
    })
  }
  export const formatRoutes = (routes) => {
    let fmRoutes = [];
    routes.forEach(router => {
      let {
        path,
        component,
        name,
        iconCls,
        children,
      } = router;
      if (children && children instanceof Array) {
        //递归
        children = formatRoutes(children);
      }
      let fmRouter = {
          path: path,
          name: name,
          iconCls: iconCls,
          children: children,
          component(resolve) {
            if (component.startsWith('Home'))
            {
              require(['../views/' + component + '.vue'], resolve);
            }else if (component.startsWith('Enroll'))
            {
              require(['../views/' + component + '.vue'], resolve);
            }else if (component.startsWith('Main'))
            {
              require(['../views/' + component + '.vue'], resolve);
            }else if (component.startsWith('Data'))
            {
              require(['../views/data/' + component + '.vue'], resolve);
            }else if (component.startsWith('Good'))
            {
              require(['../views/good/' + component + '.vue'], resolve);
            }
            else if (component.startsWith('Per')) {
              require(['../views/per/' + component + '.vue'], resolve);
            }
            else if (component.startsWith('Rent')) {
              require(['../views/rent/' + component + '.vue'], resolve);
            }
            else if (component.startsWith('Sys')) {
              require(['../views/sys/' + component + '.vue'], resolve);
            }
            else if (component.startsWith('Comfirm')) {
              require(['../views/comfirm/' + component + '.vue'], resolve);
            }
            else if (component.startsWith('Security')) {
              require(['../views/suy/' + component + '.vue'], resolve);
            }

          }
      }
      fmRoutes.push(fmRouter);
    })
    return fmRoutes;
  }
